//网易云信
import ENVIRONMENT_CONFIG from '@/pages/subPage/liveVideoArea/nim/config/envConfig'
import PAGE_CONFIG from '@/pages/subPage/liveVideoArea/nim/config/pageConfig'

import createStore from '@/pages/subPage/liveVideoArea/nim/redux/createStore'
import reducer from '@/pages/subPage/liveVideoArea/nim/store/reducer'

const store = createStore(reducer) // redux store
import WeAppRedux from '@/pages/subPage/liveVideoArea/nim/redux/index'

const {Provider} = WeAppRedux
import log from '@/utils/log' // 引用上面的log.js文件
import IMController from '@/pages/subPage/liveVideoArea/nim/controller/im'
import storage from '@/utils/storage'
import {filterTime} from "./index";
const $store = require('@/store/index.js')

const msgStatus_sending='sending'//发送中
const msgStatus_fail='fail'//发送失败
const msgStatus_success='success'//发送成功


/**
 * 初始化
 */
function init () {
  Provider(store)
  getApp().store = store
  let systemInfo = wx.getSystemInfoSync()
  getApp().globalData = {
    emitter: null,
    netcallController: null,
    isPushBeCallPage: false,
    ENVIRONMENT_CONFIG,
    PAGE_CONFIG,
    videoContainerSize: {
      width: systemInfo.windowWidth,
      height: systemInfo.windowHeight
    }
  }
}

/**
 * 登录
 */
function login (accountInfo) {
  if (!accountInfo.netease_token || !accountInfo.netease_id) {
    return
  }
  new IMController({
    token: accountInfo.netease_token,
    account: accountInfo.netease_id
  })
}

/**
 * 发送消息
 * @param options
 * {
    to: '18911564453459600.kf',
    text: 'hello',
    done: sendMsgDone
  }
 */
function sendText (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return
  }
  options.scene = 'p2p'
  let nim = getApp().globalData.nim
  // console.log(nim, 'nim')
  try{
    let localMsg = nim.sendText(options);
    let localMsgArr = storage.getLocalMsg();
    localMsgArr.push(localMsg)//云信生成初始文本消息状态是sending
    storage.setLocalMsg(localMsgArr)
    return localMsg
  }catch (e) {
    reconnection()

    let localMsg = createLocalMsg(options);
    localMsg.status=msgStatus_fail//手动生成文本消息状态是fail
    //手动生成文本消息状态填充字段
    localMsg.type='text'
    localMsg.from=nim.account
    let localMsgArr = storage.getLocalMsg();
    localMsgArr.push(localMsg)
    storage.setLocalMsg(localMsgArr)
    // setTimeout(()=>{
    //   nim.sendText(options)
    // },10*1000)
    return localMsg
  }

  // console.log('正在发送p2p text消息, id=' + msg.idClient)
}

/**
 * 生成发送中msg
 * @param options
 * @returns {void|undefined|*}
 */
function createLocalMsg(options){
  /**
   *
   custom: "{"regular_id":"794","category":"4","aptId":"E2002210001"}"
   flow: "out"
   from: "255134195171771579182454653"
   fromClientType: "Web"
   fromDeviceId: "ef6a64ca4599a47ba0a790d59c5b76f3"
   fromNick: "王莹颖"
   idClient: "2b034a5d8ba3f7641a53e5d07760d635"
   isHistoryable: true
   isLocal: false
   isOfflinable: true
   isPushable: true
   isReplyMsg: true
   isRoamingable: true
   isSyncable: true
   isUnreadable: true
   needMsgReceipt: false
   needPushNick: true
   resend: false
   scene: "p2p"
   sendStatus: 0
   sessionId: "p2p-323132688067431575257015223"
   status: "sending"
   target: "323132688067431575257015223"
   text: "1"
   time: 1582301169048
   to: "323132688067431575257015223"
   type: "text"
   */

  /**
   scene: 'p2p',
   to: self.chatTo,
   text: text,
   custom: JSON.stringify(newObject),
   */

  /**
   type: 'image',
   scene: 'p2p',
   to: to,
   custom: JSON.stringify(custom),
   wxFilePath: files[i],
   * @type {{}}
   */


  let msg={}
  Object.assign(msg,options)
  msg.time=new Date().getTime()
  msg.sessionId=options.scene+'-'+options.to
  if (!msg.idClient){
    msg.idClient=msg.time
  }

  if (msg.type=='image'){
    msg.localFilePath=options.wxFilePath || options.filePath
    msg.file={
      w:200,
      h:200,
      url:msg.localFilePath
    }
  }else if (msg.type=='audio'){
    msg.localFilePath=options.wxFilePath || options.filePath
    msg.file={
      dur:options.duration,
      name:msg.localFilePath
    }
  }
  return msg
}


// 发送文件
function sendFile (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return
  }
  options.scene = 'p2p'
  let nim = getApp().globalData.nim
  try{
     nim.sendFile(options)

    options.status=msgStatus_sending
    let localMsg = createLocalMsg(options);
    let localMsgArr = storage.getLocalMsg();
    localMsgArr.push(localMsg)
    storage.setLocalMsg(localMsgArr)
    return localMsg
  }catch (e) {
    reconnection()
    options.status=msgStatus_fail
    let localMsg = createLocalMsg(options);
    let localMsgArr = storage.getLocalMsg();
    localMsgArr.push(localMsg)
    storage.setLocalMsg(localMsgArr)
    return localMsg
  }
}

/**
 * 呼叫
 * @param options
 * {
          callee: '18911564453459600.kf', // 被叫账号
        }
 */
function callVideo (options) {
  if (options === undefined || options === null) {
    console.log('呼叫失败，参数不能为null')
    return
  }
  options.type = 2// 通话类型：1音频，2视频
  options.forceKeepCalling = true// 持续呼叫
  let netcall = getApp().globalData.netcall
  // // fixme 在外部手动设置超时计时器
  // let callTimer = setTimeout(function () {
  //   // 请在对方处理后，清除呼叫定时器，否则将执行挂断逻辑
  //   console.log('超时未接听, hangup')
  //   netcall.hangup()
  //   options.error('超时未接听')
  // }, 1000 * 60)

  netcall
    .call(options)
    // .then(function () {
    //   // 成功发起呼叫
    //   console.log('呼叫成功！')
    // })
    .catch(function (err) {
      console.error('呼叫失败！',err)
      if (options.error){
        options.error(err)
      }
    })

}

/**
 * 挂断
 */
function hangup () {
  getApp().globalData.netcall.hangup()
}
/**
 * 挂断
 */
function disconnect () {
  getApp().globalData.netcall.disconnect()
}

//销毁
function destroy(options) {
  try{
    getApp().globalData.nim.destroy(options)
  }catch (e) {
    console.log('发送失败，重连')
    reconnection()
  }

}

// 重连 解决直接使用重连方法报错，
function reconnection () {
  let info = storage.getAccountInfo() ? storage.getAccountInfo() : ''
  log.info('云信重连', info)
  try {
    login(info)
  } catch (e) {
  }

  // try {
  //   getApp().globalData.nim.connect()
  // } catch (error) {
  //   let status = $store.default.state.loginStatus // im登录状态
  //   if (!status) {
  //     let info = storage.getAccountInfo() ? storage.getAccountInfo() : ''
  //     if (info) {
  //       getApp().globalData.nim.destroy({
  //         done: function () {
  //           login(info)
  //         }
  //       })
  //     }
  //   }
  // }
}

//结束问诊提醒
function finisApt (item) {
  let app = getApp()
  let newObject = {
    // 多个就诊人区分
    regular_id: item.regular_id + '',
    category: item.category + '',
    aptId: item.apt_id,
    finishApt: true
  }
  try {
    app.globalData.nim.sendTipMsg({
      scene: 'p2p',
      to: item.netease_id,
      tip: '您的问诊已结束,感谢使用!',
      isUnreadable: false,
      custom: JSON.stringify(newObject),
      done: (err, msg) => {}
    })
  } catch (e) {
    console.log('发送失败，重连')
    reconnection()
  }
}
// 重置未读数
function resetSessionUnread (session) {
  try {
    let nim = getApp().globalData.nim
    nim.resetSessionUnread(session)
  } catch (e) {
    console.log('重置未读数失败，重连')
    reconnection()
  }
}
function getHistoryMsgs (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return null
  }
  let nim = getApp().globalData.nim
  // console.log(nim, 'nim')
  if(options.beginTime){//开始时间
    options.beginTime=options.beginTime*1000
  }else {
    delete options.beginTime
  }
  if(options.endTime){//结束时间
    options.endTime=options.endTime*1000
  }else {
    delete options.endTime
  }
  if (!options.reverse){
    options.reverse= true// 时间倒序排序
  }

  try {
    nim.getHistoryMsgs(options)
  } catch (e) {
    console.log('获取历史记录失败，重连')
    reconnection()
  }
}
function deleteMsg (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return null
  }
  let nim = getApp().globalData.nim
  // console.log(nim, 'nim')
  try {
    nim.deleteMsg(options)
  } catch (e) {
    console.log('删除失败，重连')
    reconnection()
  }
}
// 删除云端的消息
function deleteSession (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return null
  }
  let nim = getApp().globalData.nim
  // console.log(nim, 'nim')
  try {
    nim.deleteSession(options)
  } catch (e) {
    console.log('删除服务器会话失败')
    reconnection()
  }
}
// 删除本地的消息
function deleteLocalMsgs (options) {
  if (options === undefined || options === null) {
    console.log('发送失败，参数不能为null')
    return null
  }
  let nim = getApp().globalData.nim
  // console.log(nim, 'nim')
  try {
    nim.deleteLocalMsgs(options)
  } catch (e) {
    console.log(e)
    console.log('删除本地的消息失败')
    // reconnection()
  }
}
export default {
  init,
  login,
  sendText,
  callVideo,
  hangup,
  sendFile,
  disconnect,
  reconnection,
  finisApt,
  destroy,
  resetSessionUnread,
  getHistoryMsgs,
  deleteMsg,
  msgStatus_sending,
  msgStatus_fail,
  msgStatus_success,
  deleteSession,
  deleteLocalMsgs
}
